from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Book, Author

# Create your views here.

# 图书列表
class BookListView(ListView):
    model = Book
    template_name = 'library/book_list.html'
    context_object_name = 'books'
    paginate_by = 5

    def get_queryset(self):
        queryset = super().get_queryset()
        q = self.request.GET.get('q')
        if q:
            queryset = queryset.filter(title__icontains=q)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['q'] = self.request.GET.get('q', '')
        return context

# 图书详情
class BookDetailView(DetailView):
    model = Book
    template_name = 'library/book_detail.html'
    context_object_name = 'book'

# 添加图书
class BookCreateView(CreateView):
    model = Book
    fields = ['title', 'author', 'published_date', 'isbn', 'summary']
    template_name = 'library/book_form.html'
    success_url = reverse_lazy('book-list')

# 编辑图书
class BookUpdateView(UpdateView):
    model = Book
    fields = ['title', 'author', 'published_date', 'isbn', 'summary']
    template_name = 'library/book_form.html'
    success_url = reverse_lazy('book-list')

# 删除图书
class BookDeleteView(DeleteView):
    model = Book
    template_name = 'library/book_confirm_delete.html'
    success_url = reverse_lazy('book-list')

# 作者列表
class AuthorListView(ListView):
    model = Author
    template_name = 'library/author_list.html'
    context_object_name = 'authors'
    paginate_by = 5

    def get_queryset(self):
        queryset = super().get_queryset()
        q = self.request.GET.get('q')
        if q:
            queryset = queryset.filter(name__icontains=q)
        return queryset

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['q'] = self.request.GET.get('q', '')
        return context

# 添加作者
class AuthorCreateView(CreateView):
    model = Author
    fields = ['name', 'bio']
    template_name = 'library/author_form.html'
    success_url = reverse_lazy('author-list')

# 编辑作者
class AuthorUpdateView(UpdateView):
    model = Author
    fields = ['name', 'bio']
    template_name = 'library/author_form.html'
    success_url = reverse_lazy('author-list')

# 删除作者
class AuthorDeleteView(DeleteView):
    model = Author
    template_name = 'library/author_confirm_delete.html'
    success_url = reverse_lazy('author-list')

# 作者增删改可用Django后台管理，或后续补充前端页面
